<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>验证码</title>
    <script src="https://lib.baomitu.com/fingerprintjs2/2.1.5/fingerprint2.js"></script>
</head>
<style>
    .main {
        width: 800px;
        margin: 0 auto;
        padding-top: 100px;
    }
    
    .code {
        height: 40px;
        line-height: 40px;
        padding: 0 4px;
        box-sizing: border-box;
        outline: 0;
        font-size: 16px;
    }
    
    .code-img {
        vertical-align: middle;
        margin-left: 10px;
    }
    
    .btn {
        cursor: pointer;
        color: #fff;
        background-color: #409eff;
        border: 1px solid #409eff;
        text-align: center;
        box-sizing: border-box;
        outline: 0;
        margin: 0;
        font-weight: 500;
        padding: 12px 20px;
        font-size: 14px;
        border-radius: 4px;
    }
</style>

<body>
    <div class="main">
        <div>
            <input type="text" class="code" id="code">
            <sapn class="code-img" id="codeImg" onclick="getCodeImg()"></sapn>
        </div>
        <button class="btn" id="verificationBtn">验证</button>
    </div>
</body>

</html>

<script>
    let browserId = ''; //定义浏览器id全局变量
    window.onload = function() {
        getFingerprint().then(res => {
            browserId = res;
            getCodeImg();
        })
    }
    async function getCodeImg() {
        // 请求接口获取验证码数据
        // fetch 默认是get请求
        let response = await fetch('http://127.0.0.1:3000/getCodeImg?browserId=' + browserId);
        response.json().then(res => {
            document.querySelector('#codeImg').innerHTML = res.data; //渲染验证码图片
        })
    }
    // 获取浏览器指纹
    function getFingerprint() {
        // 因为是异步的所以使用 Promise
        return new Promise((resolve, reject) => {
            // 浏览器指纹
            Fingerprint2.get((components) => {
                const values = components.map(component => component.value);
                const murmur = Fingerprint2.x64hash128(values.join(''), 31); // 生成浏览器指纹
                resolve(murmur)
            });
        })
    }
    // 验证
    document.querySelector('#verificationBtn').addEventListener('click', async function() {
        let code = document.querySelector('#code').value
        let param = {
            browserId: browserId,
            code: code
        }
        let response = await fetch('http://127.0.0.1:3000/validationCode', {
            method: "POST",
            body: JSON.stringify(param)
        })
        response.json().then(res => {
            alert(res.msg)
        })
    })
</script>